package org.gtiles.components.login.ext;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.MapType;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
/**
 * 
 * Title: UserServiceClient<br>
 * Description: 访问单体登录服务<br>
 * Copyright @ 2011~2018 Goldgov .All rights reserved.<br>
 * 
 * @author GuoR
 * @createDate 2018年2月13日
 */
@Service
public class LoginServiceClient {
	@HystrixCommand(fallbackMethod = "loginFallback")
	public LoginAuthBean getLoginInfoByLoginID(String loginID) {
		RestTemplate restTemplate = new RestTemplate() ;
		Map<String, Object> map = new HashMap<String,Object>();
	    map.put("loginID", loginID);
	    map.put("loginWay",1);
	    LoginAuthBean loginAuthBean =null;
	    try {
	    	String body = restTemplate.getForEntity("http://shanxue:8080/user/userinfoByLoginID.json?loginID={loginID}&loginWay={loginWay}",String.class,map).getBody();
			ObjectMapper objectMapper = new ObjectMapper();
			MapType constructMapType = objectMapper.getTypeFactory().constructMapType(HashMap.class, String.class, Object.class);
			HashMap<String,Object> props= objectMapper.readValue(body, constructMapType);
			Boolean success = (Boolean)props.get("success");
			if(success&&!ObjectUtils.isEmpty(props.get("data"))) {
				loginAuthBean = initBean((Map)props.get("data"));
			}
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return loginAuthBean;
	}
	private LoginAuthBean initBean(Map data) {
		//{userId=352b0288-6e5b-11e6-a1f9-507b9dbfbcab, userName=demo1, name=demo1, headPhoto=121, accountId=352a7175-6e5b-11e6-a1f9-507b9dbfbcab, account=demo1, password=21218cca77804d2ba1922c33e0151105, accountState=1}
		LoginAuthBean loginAuthBean = new LoginAuthBean();
		loginAuthBean.setAccount((String)data.get("account"));
		loginAuthBean.setAccountId((String)data.get("accountId"));
		loginAuthBean.setAccountState((int)data.get("accountState"));
		loginAuthBean.setUserId((String)data.get("userId"));
		loginAuthBean.setUserName((String)data.get("userName"));
		loginAuthBean.setName((String)data.get("name"));
		loginAuthBean.setHeadPhoto((String)data.get("headPhoto"));
		loginAuthBean.setPassword((String)data.get("password"));
		loginAuthBean.setNickName((String)data.get("nickName"));
		return loginAuthBean;
	}
	public String loginFallback() {
		return "hello error";
	}
}
